import express from 'express';
import fetch from 'node-fetch';
import dotenv from 'dotenv';

dotenv.config();

const {
  SHOPIFY_API_KEY='86038e24cea7f38cb36a91dca25dd4a0',
  // SHOPIFY_API_SECRET='shpat_1234567890',
  SHOPIFY_API_SECRET='f57888aaac30bd27fdef6aaec45005cc',
  SCOPES='write_products, read_themes, write_themes',
  APP_URL='https://lift-delivers-bond-gasoline.trycloudflare.com',
  PORT = 3000,
} = process.env;

if (!SHOPIFY_API_KEY || !SHOPIFY_API_SECRET || !APP_URL) {
  console.error('Missing env SHOPIFY_API_KEY/SHOPIFY_API_SECRET/APP_URL');
  process.exit(1);
}

const app = express();
app.use(express.json());

// 简单内存存储（仅用于测试）
const shopToToken = new Map();

// 1) 发起授权：/auth?shop=my-shop.myshopify.com
app.get('/auth', (req, res) => {
  const shop = req.query.shop;
  if (!shop) return res.status(400).send('Missing ?shop');

  const state = Math.random().toString(36).slice(2);
  const redirectUri = `${APP_URL.replace(/\/$/, '')}/auth/callback`;
  const params = new URLSearchParams({
    client_id: SHOPIFY_API_KEY,
    scope: SCOPES || '',
    redirect_uri: redirectUri,
    state,
  });

  const authorizeUrl = `https://${shop}/admin/oauth/authorize?${params.toString()}`;
  return res.redirect(authorizeUrl);
});

// 2) 回调换 token：Shopify 重定向到此处
app.get('/auth/callback', async (req, res) => {
  try {
    const { shop, code } = req.query;
    if (!shop || !code) {
      return res.status(400).send('Missing shop or code');
    }

    const tokenUrl = `https://${shop}/admin/oauth/access_token`;
    const resp = await fetch(tokenUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_id: SHOPIFY_API_KEY,
        client_secret: SHOPIFY_API_SECRET,
        code,
      }),
    });

    const data = await resp.json();
    if (!resp.ok) {
      return res
        .status(resp.status)
        .send(`Exchange failed: ${data?.error || 'unknown error'}`);
    }

    // data: { access_token, scope, ... }
    shopToToken.set(shop, data.access_token);

    return res.send(`
      <html>
        <body style="font-family: sans-serif">
          <h3>授权成功</h3>
          <p>Shop: ${shop}</p>
          <p>已获取 access_token（保存在服务端内存中，仅用于测试）。</p>
          <p><a href="/api/token?shop=${encodeURIComponent(shop)}">查看 token（测试）</a></p>
          <p><a href="/api/products?shop=${encodeURIComponent(shop)}">请求 products（测试）</a></p>
        </body>
      </html>
    `);
  } catch (err) {
    console.error('Callback error', err);
    return res.status(500).send('Callback error');
  }
});

// 3) 查看当前 token（测试用，勿用于生产）
app.get('/api/token', (req, res) => {
  const { shop } = req.query;
  if (!shop) return res.status(400).json({ success: false, error: 'Missing shop' });
  const token = shopToToken.get(shop);
  if (!token) return res.status(404).json({ success: false, error: 'Token not found' });
  return res.json({ success: true, shop, access_token: token });
});

// 4) 用 token 调用 Admin API（示例：获取产品）
app.get('/api/products', async (req, res) => {
  try {
    const { shop } = req.query;
    if (!shop) return res.status(400).json({ success: false, error: 'Missing shop' });
    const token = shopToToken.get(shop);
    if (!token) return res.status(404).json({ success: false, error: 'Token not found' });

    const resp = await fetch(`https://${shop}/admin/api/2024-01/products.json`, {
      headers: { 'X-Shopify-Access-Token': token },
    });
    const data = await resp.json();
    if (!resp.ok) return res.status(resp.status).json({ success: false, error: data });
    return res.json({ success: true, products: data.products || [] });
  } catch (err) {
    console.error('Products error', err);
    return res.status(500).json({ success: false, error: 'Unexpected error' });
  }
});

app.listen(PORT, () => {
  console.log(`OAuth test server listening at http://localhost:${PORT}`);
  console.log(`Start auth: http://localhost:${PORT}/auth?shop=my-shop.myshopify.com`);
});


